import FlowCanvas from '@/pages/components/flow-canvas/index.jsx'
import { findInstanceOrBranchDetail } from '@/api/project-flow.js'
import { useEffect, useState, useRef } from 'react'
import { useParams } from 'react-router'
import { nodeConfigByIcon } from '@/pages/components/flow-canvas/nodes.js'
import { NODE_TYPE_ROOT} from '@/utils/constant.js'

// 1测试用例 2 分支 3 流程
const TestCaseFlowDesigner = () => {
  const { id } = useParams()
  const [caseData, setCaseData] = useState(null)
  const designerRef = useRef(null)

  const requestDetail = () => {
    findInstanceOrBranchDetail({ id }).then((res) => {
      if (res.data.instanceContent) {
        res.data.instanceContent = JSON.parse(res.data.instanceContent)
      } else {
        res.data.instanceContent = {
          cells: [],
        }
      }
      res.data.canvasType = '1'
      setCaseData(res.data)
    })
  }

  useEffect(() => {
    requestDetail()
  }, [id])


  const stencilPannelList = [
    {
      typeCode: '8',
      templateType: '8',
      templateName: '分支',
    }
  ]

  const afterGraphInit = (graph, modelData, callback) => {
    if (modelData.cells.length == 0 && caseData) {
      let node = graph.createNode({
        id: caseData.id,
        x: graph.options.width / 2,
        y: 10,
        ...nodeConfigByIcon(caseData.instanceName, 'ks'),
        data: {
          id: caseData.id,
          nodeType: NODE_TYPE_ROOT,
          typeCode: '1',
          templateId: caseData.template_id,
          templateCode: caseData.template_code, // 暂未返回
          templateIcon: 'ks',
          templateType: '7',
          templateName: caseData.instanceName,
          typeId: caseData.typeId
        },
      })
      graph.addNode(node)
      callback && callback()
    }
  }

  const menuConifg = {
    menuItems(graph, node) {
      let list = []
      return list
    },
    menuClick(key, graph, node, point) {
      switch (key) {
        default:
          break
      }
    },
  }

  return (
    <FlowCanvas
      ref={designerRef}
      pageTitle={(caseData ? `【${caseData.instanceName}】` : '') + '用例'}
      menuConifg={menuConifg}
      modelData={caseData}
      stencilPannelList={stencilPannelList}
      afterGraphInit={afterGraphInit}
      showChildren={true}
    />
  )
}

export default TestCaseFlowDesigner
